<?php
namespace App\Api\Controller;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
use App\Constant\AliPay;
use App\Models\Bindwallet;
use App\Models\Order;
use App\Models\PayLogs;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use ModStart\Core\Input\InputPackage;
use Module\Member\Support\MemberLoginCheck;
use ModStart\Core\Input\Response;


class AlipayController extends Controller implements MemberLoginCheck
{

    public static $memberLoginCheckIgnores = ['notify','pay','returnBack','withdrawal'];

    /***
     * 支付
     */
    public function pay()
    {
        $input = InputPackage::buildFromInput();
        $order_Id = $input->getInteger('order_Id');
        $pay_type = $input->getInteger('pay_type');
        $data = [];
        $data['order_id'] = $order_Id;
        $data['pay_type'] = $pay_type;
        if (empty($data['order_id'])) {
            return Response::jsonError("订单id为空");
        }
        if (empty($data['pay_type'])) {
            return Response::jsonError("支付方式不能为空");
        }
        $info = (new Order())->getOrderInfo($data['order_id']);
        if ($info->add_type != 1) {
            return Response::jsonError("该订单类型有误,不能执行储蓄操作!");
        }
        $info->pay_type = $data['pay_type'];
        $info->save();
        if ($data['pay_type'] == 1) {

        } elseif ($data['pay_type'] == 2) {
            $dat['sn'] = $info->sn;
            $dat['pay_price'] = $info->money;
            $result = AliPay::payStart($dat);
            if (is_string($result)) {
                return Response::generateSuccessData([
                    'pay_str' => $result,
                ]);
            } else {
                return Response::jsonError("储蓄失败!");
            }
        }
    }

    /**
     * 退款
     */
    public function refund()
    {
        $dat['sn'] = "202410281731584258";
        $dat['back_sn'] = "2024102817315842581";
        $dat['money'] = "0.01";

        AliPay::doReturn($dat);

    }





    /**
     * 提现
     */
    public function withdrawal()
    {
       $dd = $this->GetMonth(0);
       dd($dd);
//        $dat['alipay_name'] = "梁闯";
//        $dat['alipay_account'] = "15690469916";
//        $dat['money'] = "0.2";
        $result = AliPay::withdrawal($dat);
        dd($result);

    }




    public function GetMonth($sign="0") {
        //得到系统的年月
        $tmp_date=date("Ym");
        //切割出年份
        $tmp_year=substr($tmp_date,0,4);
        //切割出月份
        $tmp_mon =substr($tmp_date,4,2);
        $tmp_nextmonth=mktime(0,0,0,$tmp_mon+$sign,1,$tmp_year);
        $tmp_month=mktime(0,0,0,$tmp_mon,1,$tmp_year);
        if($sign>0){
            //得到当前月的下一个月
            return $fm_next_month=date("Y-m",$tmp_nextmonth);
        }elseif($sign<0){
            //得到当前月的上一个月
            return $fm_forward_month=date("Y-m",$tmp_nextmonth);
        }elseif ($sign==0){
            return $fm_forward_month=date("Y-m",$tmp_month);
        }
    }




    /**
     * 回调地址
     */
    public function notify()
    {
        $input = InputPackage::buildFromInput();
        $post = $input->all();
        $this->writeLog(['data'=>'start..$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$']);
        $this->writeLog(json_encode($post));
        $this->writeLog(['data'=>'end..##################################################']);
        //想先注释后放开
        Factory::setOptions(self::getOptions());
//        $res = Factory::payment()->common()->verifyNotify($post);
        $res = Factory::payment()->common()->verifyNotify($post);
//        $this->writeLog(['data'=>'5555555555555555555555555555555555555555555'.$res]);
//        $this->writeLog(['data'=>'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'.json_encode($res)]);
//        $res = true;
        if (($post['trade_status'] = "TRADE_SUCCESS") && ($res == true)) {
                // 处理支付成功的情况
                // 根据返回的订单号查询订单数据
                $order = (new Order())->where(['sn'=> $post['out_trade_no']])->first();
                if (empty($order)) {
                    echo 'fail';
                    die("fail");
                }
                if ($order->pay_status == 1) {
                    echo 'success';die();
                }
                try {
                    DB::beginTransaction(); // 开始事务
                    $list['pay_time'] = date("Y-m-d H:i:s", time());
                    $list['pay_status'] = 1;
                    $list['order_status'] = 1;
                    (new Order())->where(['id' =>$order->id])->update($list);
                    (new Bindwallet())->where(["user_id" => $order->user_id, 'blog_id' => $order->e_blog_id])->increment("rmb_price", $order->money);
                    $log_pay['sn'] = $post['out_trade_no'];
                    $log_pay['user_id'] = $order->user_id;
                    $log_pay['order_id'] = $order->id;
                    $log_pay['money'] = $order->money;
                    $log_pay['type'] = 1;
                    $log_pay['pay_type'] = 2;
                    $log_pay['trade_no'] = $post['trade_no'];
                    $log_pay['pay_time'] = date("Y-m-d H:i:s", time());
                    $log_pay['created_at'] = date("Y-m-d H:i:s", time());
                    $log_pay['updated_at'] = date("Y-m-d H:i:s", time());
                    $log_pay['remark'] = "支付宝储值";
                    $log = (new PayLogs())->where(['order_id'=>$order->id,'type'=>1,'pay_type'=>2])->first();
                    if(!$log){
                        (new PayLogs())->insert($log_pay);
                    }
                    DB::commit(); // 提交事务
                    echo 'success';
                    die();
                } catch (Exception $e) {
                    echo 'fail';
                    DB::rollback(); // 回滚事务
                    die("fail");
                }
        } else {
            echo 'fail';
        }
    }


    /**
     * 写入删除log
     */
    public function writeLog($data) {
        $filepath = base_path() . "/storage/logs/alipay/";
        if (!is_dir($filepath)) {
            mkdir($filepath);
        }
        $filename = "del_log" . date("Ymd") . ".txt";
        $file = $filepath . $filename;
        if (is_file($file)) {
            chmod($file, 0777);
            $fh = fopen($file, "a+");
        } else {
            $fh = fopen($file, "a+");
            chmod($file, 0777);
        }
        if(is_array($data)){
            $content = json_encode($data);
        }else{
            $content = $data;
        }
        if ($fh) {
            fwrite($fh, date("Y-m-d H:i:s") . ": $content \r\n");
        }
        fclose($fh);
    }

    /***
     * @return Config
     * 封装参数
     */
    private static function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = getenv('ALY_APPID');//'<-- 请填写您的AppId，例如：2019022663440152 -->';
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = getenv('merchantPrivateKey');//'<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->';
        $options->alipayCertPath = getenv('alipayCertPath');// '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
        $options->alipayRootCertPath = getenv('alipayRootCertPath');// '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
        $options->merchantCertPath = getenv('merchantCertPath');// '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
//        $options->alipayPublicKey = config('omnipay.options.public_key');//'<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->';
        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = getenv('ALY_NOTIFY');//"<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";
        return $options;
    }













}